// pages/evaluation/question/evaluation-question.js
const { api } = require('../../../utils/api');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    grade: 0,
    gradeName: '',
    questionArray: [],
    activeTab: 0,
    notCompletedTips: '答题完毕后, 可生成评测报告!',
    nickName: ''  // 添加用户名字段
  },

  // 添加定时器变量
  focusTimer: null,
  observer: null,

  /**
   * 生命周期函数--监听页面加载 
   */
  onLoad(options) {
    const grade = options.grade;
    const gradeName = decodeURIComponent(options.gradeName);
    this.setData({ grade, gradeName });
    this.fetchQuestionList();

    // 从本地存储获取用户名
    const nickName = wx.getStorageSync('nickName') || '';
    this.setData({
      nickName,
      notCompletedTips: this.getNotCompletedTips(nickName)
    });
  },

  async fetchQuestionList() {
    try {
      const params = {
        grade: this.data.grade,
        pageNo: 1,
        pageSize: 100
      };

      const res = await api.get('/teaching/xiaochengxuTestPower/getTestQuestionByGrade', params);
      console.log('res', res)
      if (res && res.result) {
        const questions = res.result.records.map((item, index) => {
          // 构建选项数组
          const options = [];
          for (let i = 1; i <= 4; i++) {
            const optionContent = item[`option${i}`];
            const optionStar = item[`option${i}Star`];
            if (optionContent) {
              options.push({
                questionId: item.id,
                name: String.fromCharCode(64 + i) + '.' + item[`option${i}`],
                value: i - 1,
                content: optionContent,
                star: optionStar,
                checked: false
              });
            }
          }

          return {
            id: item.id,
            no: index < 9 ? ('0' + (index + 1)) : (index + 1),
            question: item.content,
            title: item.title,
            options: options,
            right: item.answer,
            answer: void 0,
            power: item.power
          };
        });

        this.setData({ questionArray: questions });
        this.checkNotAnswerQuestion();
      }
    } catch (error) {
      console.error('获取问题列表失败：', error);
      wx.showToast({
        title: '获取问题列表失败',
        icon: 'none'
      });
    }
  },

  // 处理姓名输入
  onNameInput(e) {
    const nickName = e.detail.value.trim();
    this.setData({
      nickName,
      notCompletedTips: this.getNotCompletedTips(nickName)
    });
    // 保存到本地存储
    wx.setStorageSync('nickName', nickName);
  },

  // 获取未完成提示
  getNotCompletedTips(nickName) {
    if (!nickName) {
      return '请输入您的姓名';
    }

    // 检查是否所有题目都已回答
    for (let i = 0; i < this.data.questionArray.length; i++) {
      const question = this.data.questionArray[i];
      if (question.answer === undefined) {
        return `第${question.no}题, 尚未作答`;
      }
    }
    return null;
  },

  checkNotAnswerQuestion() {
    this.setData({
      notCompletedTips: this.getNotCompletedTips(this.data.nickName)
    });
  },

  tapGenerate() {
    if (!this.data.nickName) {
      wx.showToast({
        title: '请先输入您的姓名',
        icon: 'none'
      });
      return;
    }
    getApp().globalData.evaluationQuestionArray = this.data.questionArray;
    getApp().globalData.nickName = this.data.nickName; // 保存用户名到全局
    wx.navigateTo({
      url: `/pages/evaluation/report/evaluation-report?gradeName=${this.data.gradeName}&nickName=${this.data.nickName}`
    });
  },

  onTabClick(e) {
    const index = e.detail.index
    console.log('tabClick', index)
  },

  onQuestionAnswer(e) {
    console.log('onQuestionAnswer', e);
    const { answer, answerOption } = e.detail;
    for (let i = 0; i < this.data.questionArray.length; i++) {
      const question = this.data.questionArray[i];
      if (question.id === answerOption.questionId) {
        question.answer = answer;
        console.log('question', question, e.detail)
        break;
      }
    }
    this.checkNotAnswerQuestion();
  },

  onChange(e) {
    const index = e.detail.index
    // console.log('change', index)
  },
  handleClick() {
    wx.navigateTo({
      url: '../tabs/webview',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})